package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listenter.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    //自动注入表格导入数据listener
    @Autowired
    private DictListener dictListener;


    //根据数据id查询子数据列表
    //redis存储数据 名=dict：：selectIndexList 值=List<Dict>
    @Cacheable(value = "dict", key = "'selectIndexList'+#id")
    @Override
    public List<Dict> findChildData(Long id) {
        //根据id查询子数据
        QueryWrapper<Dict> wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //记得表格里面没有实体类hasChildren字段
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            //判断有没有子数据
          boolean  hasChildren= this.hasChildrenById(dictId);
         dict.setHasChildren(hasChildren);
        }
        return dictList;
    }
    //判断有没有子数据
    private boolean hasChildrenById(Long dictId) {
        QueryWrapper<Dict> wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id", dictId);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }

    //导出数据
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            // 1设置文件参数
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            //查询数据 查询所有  所以wrapper为null
            List<Dict> dictList = baseMapper.selectList(null);
          List<DictEeVo> dictEeVoList = new ArrayList<>();
          //因为泛型不一样  需要把dictList给dictEeVos
            for (Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict,dictEeVo);
                dictEeVoList.add(dictEeVo);
            }
            //导出数据
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet().doWrite(dictEeVoList);

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    //导入
    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,dictListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new YyghException(20001,"导入失败");
        }
    }


    //获取字典数据名称根据
    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        //判断parentDictCode是否为空，如果为空 用一个参数查询
       //如果value能唯一定位一条数据 ，如：省市区等
        if(StringUtils.isEmpty(parentDictCode)){
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            if(dict!=null){
              return  dict.getName();
            }
        }else {
            //根据两个参数进行查询
            //根据dict_code 查询一级分类信息
            Dict parentDict=this.getDictByDictCode(parentDictCode);
            //根据parent——id和value查询数据
            Dict dict=baseMapper.selectOne(new QueryWrapper<Dict>()

                    .eq("parent_id",parentDict.getId())
                    .eq("value", value));
            if(dict!=null){
                return  dict.getName();
            }
        }
        return "";
    }

    //根据dictCode获取下级节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict parentDict = baseMapper.selectOne(
                new QueryWrapper<Dict>().eq("dict_code", dictCode));
        List<Dict> dictList = this.findChildData(parentDict.getId());

        return dictList;
    }

    //根据dict_code 查询一级分类信息
    private Dict getDictByDictCode(String parentDictCode){

        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dict_code", parentDictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);
        return dict;

    }

}
